<template>
  <el-container v-wechat-title="'我的书架'">
    <el-header>
      <nav-bar :loginDialogState="loginDialogState"></nav-bar>
    </el-header>
    <el-main>
      <div>我的书架</div>
      <ShelfBook v-for="book in books" :bookInfo="book"></ShelfBook>
    </el-main>
  </el-container>
</template>

<script>
import { ref, reactive, onMounted, watch, defineComponent } from "vue";
import NavBar from "@c/navBar/NavBar.vue";
import { getBooksFromShelf } from "@/api/axios/Bookshelf"
import { useStore } from "vuex"
import { CODE_KEY, CODE_SUCCESS } from "@/api/params"
import ShelfBook from "@c/shelf/ShelfBook.vue"

export default defineComponent({
  name: "BookShelf",
  components: {
    NavBar,
    ShelfBook,
  },
  setup () {
    
    const response_book_key = "books"
    const CHAPTER_NUM_KEY = "chapterNum"
    const store = useStore()
    
    const books = ref(
      // [
      //   {
      //     id: '',
      //     name: '',
      //     imgUrl: '',
      //     chapterNum: '',
      //     updated: ''
      //   }
      // ]
    )
    
    const loginDialogState = reactive({
      name: "login",
      visible: false
    })
    
    const getShelfContent = (username) => {
      // 获取书架
      getBooksFromShelf(username).then(res => {
        // 返回成功
        if(res && res.data[CODE_KEY] === CODE_SUCCESS) {
          // 赋值
          books.value = res.data[response_book_key]
          // 获取书架 记录
          let record = store.getters.getShelfRecord
          // 声明 一个 list ，为了不在 for里嵌套 for ，使用 list .indexOf 找值
          let recordIdList = []
          // 遍历
          for (let i = 0 ; i < record.length ; i ++) {
            // 所有 id 放入 list
            recordIdList.push(record[i].id)
          }
          console.log("recordIdList==>", recordIdList)
          for(let i = 0 ; i < books.value.length ; i++) {
            console.log("in")
            let index = recordIdList.indexOf(books.value[i].id);
            books.value[i].chapterNum = index < 0 ? 1 : record[index][CHAPTER_NUM_KEY]
            console.log(books.value[i].chapterNum)
          }
        }
      })
    }
    
    watch(() => store.getters.getUserInfo.username, (newValue, oldValue) => {
      if(!oldValue && newValue) {
        getShelfContent(newValue);
      } else if ( oldValue && !newValue ) {
        books.value = []
      }
    })
    
    onMounted(() => {
      let username = store.getters.getUserInfo.username
      // 已经登录
      if(username) {
        // 获取书架
        getShelfContent(username);
      } else {
        loginDialogState.visible = true
      }
    })
    
    return {
      books,
      loginDialogState
    }
  }
})

</script>

<style>
</style>
